<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>余额计算</title>
    <style>
        table { border-collapse: collapse; width: 600px; margin: 30px auto; }
        th, td { border: 1px solid #333; padding: 12px; text-align: center; }
        th { background: #f5f5f5; }
        button { display: block; margin: 20px auto; padding: 10px 25px; cursor: pointer; }
    </style>
</head>
<body>
    <button onclick="startCalculate()">点击开始（弹窗输入数据）</button>
        <h1 style="text-align: center;">消费支出</h1>
    <div id="tableBox"></div>
    <script>
        function startCalculate() {
            let total = getValidNumber("请输入银行卡总额（元）", );
            let water = getValidNumber("请输入水费（元）", );
            let electric = getValidNumber("请输入电费（元）", );
            let net = getValidNumber("请输入网费（元）", );

            let remaining = total - water - electric - net;

            alert(`计算完成！\n原总额：${total.toFixed(2)}元\n总支出：${(water+electric+net).toFixed(2)}元\n剩余余额：${remaining.toFixed(2)}元`);

            let tableHTML = `
                <table>
                    <tr><<th>银行卡原总额</</th><<th>水费</</th><<th>电费</</th><<th>网费</</th><<th>剩余余额</</th></tr>
                    <tr>
                        <td>${total.toFixed(2)}元</td>
                        <td>${water.toFixed(2)}元</td>
                        <td>${electric.toFixed(2)}元</td>
                        <td>${net.toFixed(2)}元</td>
                        <td style="color: ${remaining>=0?'green':'red'}">${remaining.toFixed(2)}元</td>
                    </tr>
                </table>
            `;
            document.getElementById("tableBox").innerHTML = tableHTML;
        }

        function getValidNumber(title, tip) {
            let value;
            while (true) {
                value = prompt(title, tip);
                if (value === null) { alert("已取消操作"); location.reload(); }
                let num = parseFloat(value);
                if (!isNaN(num) && num >= 0) { return num; }
                alert("输入错误！请填写大于等于0的数字");
            }
        }
    </script>
</body>
</html>